package com.lungle.warmdiary.app.view.me.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.Html;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.lungle.warmdiary.R;
import com.lungle.warmdiary.app.AppContext;
import com.lungle.warmdiary.app.api.remote.ApiFactory;
import com.lungle.warmdiary.app.base.BaseActivity;
import com.lungle.warmdiary.app.base.BaseDetailFragment;
import com.lungle.warmdiary.app.base.BaseSubscriber;
import com.lungle.warmdiary.app.model.Result;
import com.lungle.warmdiary.app.model.event.TesterApplyStatusChangeEvent;
import com.lungle.warmdiary.app.model.request.TesterApplyPost;
import com.lungle.warmdiary.app.model.response.TesterDetail;
import com.lungle.warmdiary.app.model.response.TesterIndustry;
import com.lungle.warmdiary.app.model.response.TesterStat;
import com.lungle.warmdiary.app.utils.LogUtils;
import com.lungle.warmdiary.app.utils.TDevice;
import com.lungle.warmdiary.app.utils.UIHelper;
import com.umeng.analytics.MobclickAgent;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.Observable;
import rx.Observer;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by zhangxueyuan on 16/10/7.
 * <p>
 * 亲测师申请页面
 * 亲测师申请拒绝再次编辑页面
 */
public class TesterApplyFragment extends BaseDetailFragment {

    public static final int REQUEST_INDUSTRY = 0x0000;

    @Bind(R.id.auditInfo_text)
    TextView auditInfoText;
    @Bind(R.id.auditInfo)
    LinearLayout auditInfoLayout;
    @Bind(R.id.industry_name)
    TextView industryName;
    @Bind(R.id.imageView)
    ImageView imageView;
    @Bind(R.id.layout_industry_name)
    LinearLayout layoutIndustryName;
    @Bind(R.id.editTextView)
    EditText editTextView;
    @Bind(R.id.num)
    TextView num;
    @Bind(R.id.industry_name_refuse)
    TextView industryNameRefuse;
    @Bind(R.id.text)
    TextView text;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(getLayoutId(), container, false);
        ButterKnife.bind(this, view);
        initData();
        initView(view);
        return view;
    }


    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(getActivity());
        if (click != null) {
            Observable.create(new Observable.OnSubscribe<String>() {
                @Override
                public void call(Subscriber<? super String> subscriber) {
                    subscriber.onNext(AppContext.getTesterApply("" + click.getIndustry()));
                }
            })
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread()) // 指定 Subscriber 的回调发生在主线程
                    .subscribe(new Observer<String>() {
                        @Override
                        public void onNext(String content) {
                            editTextView.setText(content);
                        }

                        @Override
                        public void onCompleted() {
                        }

                        @Override
                        public void onError(Throwable e) {
                            LogUtils.printLogE(e.getMessage());
                        }
                    });

        }


    }

    boolean succ = false;

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(getActivity());
        if (!succ && click != null) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    AppContext.setTesterApply(industryId, editTextView.getText().toString());
                }
            }).start();
            AppContext.showToastShort("已保存草稿");
        }
    }


    @Override
    public void initView(View view) {
        if (click != null && click.getStatus() == TesterStat.REFUSE) {
            auditInfoLayout.setVisibility(View.VISIBLE);
            layoutIndustryName.setVisibility(View.GONE);
            text.setVisibility(View.VISIBLE);

            BaseActivity activity = (BaseActivity)getActivity();
            activity.setActionBarTitle("审核未通过");
        } else {
            auditInfoLayout.setVisibility(View.GONE);
            layoutIndustryName.setVisibility(View.VISIBLE);
            text.setVisibility(View.GONE);
        }

        editTextView.addTextChangedListener(new TextWatcher() {
            private CharSequence temp;

            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            public void onTextChanged(CharSequence s, int start, int before, int count) {
                temp = s;
            }

            public void afterTextChanged(Editable s) {
                int number = MAX_NUM - s.length();
                num.setText(Html.fromHtml(String.format("还可以输入<font color=#F94848>%d</font>个字", number)));
            }
        });
    }

    List<TesterStat> pass;
    TesterStat click;


    @Override
    public void initData() {
        pass = (List<TesterStat>) getArguments().getSerializable("pass");
        click = (TesterStat) getArguments().getSerializable("click");
        if (click != null)
            industryId = "" + click.getIndustry();
    }

    private String cacheContent;

    @Override
    protected void sendRequestData() {
        if (click != null && click.getStatus() == TesterStat.REFUSE)
            ApiFactory.getUserApi().getTesterApplyDetail(click.getId()).subscribeOn(Schedulers.io())
                    .compose(this.<Result<TesterDetail>>bindToLifecycle())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new BaseSubscriber<Result<TesterDetail>>() {
                        @Override
                        public void onCompleted() {
                            hideWaitDialog();
                            super.onCompleted();
                        }

                        @Override
                        public void onNext(Result<TesterDetail> testerDetailResult) {
                            super.onNext(testerDetailResult);
                            industryNameRefuse.setText(String.format("%s 徽章未通过理由", AppContext.getIndustryName("" + click.getIndustry())));
                            if (TextUtils.isEmpty(editTextView.getText().toString())) {
                                cacheContent = testerDetailResult.getData().getDesc();
                                editTextView.setText(testerDetailResult.getData().getDesc());
                            }
                            auditInfoText.setText(testerDetailResult.getData().getAuditInfo());
                        }
                    });
    }


    @Override
    protected int getLayoutId() {
        return R.layout.fragment_apply;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);

    }

    private static final int MAX_NUM = 400;//限制的最大字数　　
    private static final int MIN_NUM = 50;//限制的最大字数　　

    private boolean presubmit() {
        if (click == null && TextUtils.isEmpty(industryId)) {
            AppContext.showToastShort("请选择行业");
            return false;
        } else if (editTextView.getText().length() < MIN_NUM) {
            if (editTextView.getText().length() == 0) {
                AppContext.showToastShort("未输入内容");
                return false;
            }

            AppContext.showToastShort(String.format("输入字数不得少于%d字", MIN_NUM));
            return false;

        } else if (editTextView.getText().length() > MAX_NUM) {
            AppContext.showToastShort(String.format("输入字数不得超过于%d字", MAX_NUM));
            return false;

        } else if (!TextUtils.isEmpty(cacheContent) && cacheContent.equals(editTextView.getText().toString())) {
            AppContext.showToastShort("内容没有修改");
            return false;
        }

        LogUtils.printLogD(cacheContent);
        LogUtils.printLogD(editTextView.getText().toString());

        return true;

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (!presubmit())
            return true;
        View view = getActivity().getWindow().peekDecorView();
        TDevice.hideSoftKeyboard(view);
        Observable<Result> observable;
        if (click != null && click.getStatus() == TesterStat.REFUSE) {
            TesterApplyPost.MediaUserTester mediaUserTester = new TesterApplyPost.MediaUserTester(click.getIndustry(), editTextView.getText().toString());
            TesterApplyPost testerApplyPost = new TesterApplyPost(mediaUserTester);
            observable = ApiFactory.getUserApi().testerApply(testerApplyPost, click.getId());
        } else {
            LogUtils.printLogD("industryId:" + industryId);
            TesterApplyPost.MediaUserTester mediaUserTester = new TesterApplyPost.MediaUserTester(Integer.parseInt(industryId), editTextView.getText().toString());
            TesterApplyPost testerApplyPost = new TesterApplyPost(mediaUserTester);
            observable = ApiFactory.getUserApi().testerApply(testerApplyPost);
        }
        observable.subscribeOn(Schedulers.io())
                .compose(this.<Result>bindToLifecycle())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<Result>() {
                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                        hideWaitDialog();
                        EventBus.getDefault().post(new TesterApplyStatusChangeEvent());
                        AppContext.showToastShort("提交成功");
                        getActivity().finish();

                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        hideWaitDialog();
                        succ = false;
                    }

                    @Override
                    public void onNext(Result result) {
                        AppContext.removeTesterApply(industryId);
                        succ = true;
                    }
                });
        return true;
    }


    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        getActivity().getMenuInflater().inflate(R.menu.active_detail, menu);
        menu.findItem(R.id.login_menu_send).setTitle("提交");
    }


    @OnClick(R.id.layout_industry_name)
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.layout_industry_name:
                if (click != null)
                    UIHelper.showTesterIndustry(this, click.getId(), REQUEST_INDUSTRY, pass);
                else
                    UIHelper.showTesterIndustry(this, "", REQUEST_INDUSTRY, pass);
                break;
        }
    }

    String industryId;


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data == null) return;
        if (requestCode == REQUEST_INDUSTRY) {//选择行业
            List<TesterIndustry> list = (List<TesterIndustry>) data.getSerializableExtra(SelectIndustryFragment.RESPONSE);
            if (list != null && list.size() > 0) {
                industryName.setText(list.get(0).getName());
                LogUtils.printLogD("industryId onActivityResult:" + industryId);
                industryId = list.get(0).getId();
            }
        }
    }


}
